<template>
  <div class="container">
    <h1 class="text-2xl font-bold mb-4">成本分析</h1>
    
    <div class="mb-4 flex items-center space-x-4">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        value-format="YYYY-MM-DD"
        @change="handleDateChange"
      />
      <el-select v-model="selectedVehicle" placeholder="选择车辆" clearable @change="loadData">
        <el-option
          v-for="vehicle in vehicles"
          :key="vehicle.id"
          :label="vehicle.vehicleNo"
          :value="vehicle.id"
        />
      </el-select>
      <el-select v-model="costType" placeholder="成本类型" clearable @change="loadData">
        <el-option label="全部" value="" />
        <el-option label="油费" value="fuel" />
        <el-option label="ETC费用" value="etc" />
        <el-option label="维修费用" value="repair" />
        <el-option label="保险费用" value="insurance" />
        <el-option label="年检费用" value="inspection" />
      </el-select>
      <el-button type="primary" @click="loadData">查询</el-button>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">总成本</h2>
        <p class="text-3xl font-bold text-red-500">{{ formatCurrency(totalCost) }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">平均每车成本</h2>
        <p class="text-3xl font-bold text-yellow-500">{{ formatCurrency(averageCostPerVehicle) }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">平均每公里成本</h2>
        <p class="text-3xl font-bold text-green-500">{{ formatCurrency(averageCostPerKm, true) }}</p>
      </el-card>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>成本分布</span>
            <el-radio-group v-model="chartType" size="small" @change="updateCharts">
              <el-radio-button label="pie">饼图</el-radio-button>
              <el-radio-button label="bar">柱状图</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="costDistributionChart" class="h-full w-full"></div>
      </el-card>
      
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>成本趋势</span>
            <el-radio-group v-model="timeUnit" size="small" @change="loadData">
              <el-radio-button label="month">月度</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
              <el-radio-button label="year">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="costTrendChart" class="h-full w-full"></div>
      </el-card>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <span>车辆成本对比</span>
          <el-radio-group v-model="vehicleCompareMode" size="small" @change="updateVehicleCompareChart">
            <el-radio-button label="total">总成本</el-radio-button>
            <el-radio-button label="average">平均成本/公里</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div ref="vehicleCompareChart" style="height: 400px; width: 100%"></div>
    </el-card>
    
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span>成本明细</span>
          <el-button type="primary" size="small" @click="exportToExcel">导出报表</el-button>
        </div>
      </template>
      <el-table :data="costRecords" border stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="costType" label="成本类型" width="120">
          <template #default="scope">
            <el-tag
              :type="getCostTypeTag(scope.row.costType)"
            >{{ getCostTypeName(scope.row.costType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="金额(元)" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.costAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="department" label="所属部门" width="120" />
        <el-table-column prop="operator" label="操作人" width="120" />
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'CostAnalysisView',
  setup() {
    // 图表实例
    let costDistributionChartInstance = null
    let costTrendChartInstance = null
    let vehicleCompareChartInstance = null
    
    // 图表DOM引用
    const costDistributionChart = ref(null)
    const costTrendChart = ref(null)
    const vehicleCompareChart = ref(null)
    
    // 数据状态
    const vehicles = ref([])
    const selectedVehicle = ref('')
    const dateRange = ref([])
    const costType = ref('')
    const chartType = ref('pie')
    const timeUnit = ref('month')
    const vehicleCompareMode = ref('total')
    const costRecords = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 统计数据
    const totalCost = ref(0)
    const averageCostPerVehicle = ref(0)
    const averageCostPerKm = ref(0)
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        },
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
      {
        text: '今年',
        value: () => {
          const end = new Date()
          const start = new Date(new Date().getFullYear(), 0, 1)
          return [start, end]
        },
      },
    ]
    
    // 模拟数据
    const mockData = {
      // 成本分布数据
      costDistribution: [
        { value: 18500, name: '油费' },
        { value: 12800, name: 'ETC费用' },
        { value: 8600, name: '维修费用' },
        { value: 6200, name: '保险费用' },
        { value: 1500, name: '年检费用' }
      ],
      // 成本趋势数据
      costTrend: {
        categories: ['1月', '2月', '3月', '4月', '5月', '6月'],
        series: [
          {
            name: '油费',
            data: [3200, 3000, 3500, 2800, 3100, 2900]
          },
          {
            name: 'ETC费用',
            data: [2200, 2000, 2300, 2100, 2000, 2200]
          },
          {
            name: '维修费用',
            data: [1500, 0, 2000, 1800, 1800, 1500]
          },
          {
            name: '保险费用',
            data: [0, 6200, 0, 0, 0, 0]
          },
          {
            name: '年检费用',
            data: [0, 1500, 0, 0, 0, 0]
          }
        ]
      },
      // 车辆成本对比
      vehicleCompare: {
        vehicles: ['京A12345', '京B67890', '京C54321', '京D98765', '京E13579'],
        totalCost: [15200, 12600, 8900, 6200, 4700],
        averageCost: [0.68, 0.75, 0.56, 0.82, 0.71]
      },
      // 成本明细记录
      costRecords: [
        {
          date: '2023-06-15',
          vehicleNo: '京A12345',
          costType: 'fuel',
          costAmount: 520,
          description: '加油95号汽油',
          department: '行政部',
          operator: '张三'
        },
        {
          date: '2023-06-12',
          vehicleNo: '京B67890',
          costType: 'etc',
          costAmount: 320,
          description: 'ETC通行费',
          department: '销售部',
          operator: '李四'
        },
        {
          date: '2023-06-10',
          vehicleNo: '京C54321',
          costType: 'repair',
          costAmount: 1500,
          description: '更换机油和机油滤芯',
          department: '技术部',
          operator: '王五'
        },
        {
          date: '2023-06-05',
          vehicleNo: '京D98765',
          costType: 'insurance',
          costAmount: 6200,
          description: '年度商业保险续保',
          department: '人事部',
          operator: '赵六'
        },
        {
          date: '2023-06-01',
          vehicleNo: '京E13579',
          costType: 'inspection',
          costAmount: 500,
          description: '年检费用',
          department: '财务部',
          operator: '钱七'
        }
      ]
    }
    
    // 初始化
    onMounted(() => {
      // 初始化日期范围为近三个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      dateRange.value = [formatDate(start), formatDate(end)]
      
      // 加载数据
      loadVehicles()
      loadData()
    })
    
    // 加载车辆列表
    const loadVehicles = async () => {
      try {
        // 实际项目中应从API获取
        /*
        const response = await axios.get('/api/vehicles')
        vehicles.value = response
        */
        
        // 模拟数据
        vehicles.value = [
          { id: 1, vehicleNo: '京A12345' },
          { id: 2, vehicleNo: '京B67890' },
          { id: 3, vehicleNo: '京C54321' },
          { id: 4, vehicleNo: '京D98765' },
          { id: 5, vehicleNo: '京E13579' }
        ]
      } catch (error) {
        ElMessage.error('获取车辆列表失败')
        console.error('获取车辆列表失败:', error)
      }
    }
    
    // 加载数据
    const loadData = async () => {
      try {
        // 实际项目中应从API获取数据
        /*
        const params = {
          startDate: dateRange.value[0],
          endDate: dateRange.value[1],
          vehicleId: selectedVehicle.value,
          costType: costType.value,
          timeUnit: timeUnit.value,
          page: currentPage.value,
          size: pageSize.value
        }
        const response = await axios.get('/api/reports/cost-analysis', { params })
        // 使用API返回的数据更新统计和图表
        */
        
        // 使用模拟数据更新
        costRecords.value = mockData.costRecords
        total.value = mockData.costRecords.length
        
        // 计算汇总数据
        calculateSummary()
        
        // 渲染图表
        nextTick(() => {
          updateCharts()
          updateVehicleCompareChart()
        })
      } catch (error) {
        ElMessage.error('加载数据失败')
        console.error('加载数据失败:', error)
      }
    }
    
    // 计算汇总数据
    const calculateSummary = () => {
      // 模拟计算总成本
      totalCost.value = mockData.costDistribution.reduce((sum, item) => sum + item.value, 0)
      
      // 模拟计算平均每车成本
      averageCostPerVehicle.value = totalCost.value / vehicles.value.length
      
      // 模拟计算每公里成本
      averageCostPerKm.value = 0.73 // 假设值
    }
    
    // 更新图表
    const updateCharts = () => {
      initCostDistributionChart()
      initCostTrendChart()
    }
    
    // 初始化成本分布图表
    const initCostDistributionChart = () => {
      if (costDistributionChartInstance) {
        costDistributionChartInstance.dispose()
      }
      
      costDistributionChartInstance = echarts.init(costDistributionChart.value)
      
      let option
      
      if (chartType.value === 'pie') {
        option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}元 ({d}%)'
          },
          legend: {
            orient: 'horizontal',
            bottom: 0,
            data: mockData.costDistribution.map(item => item.name)
          },
          series: [
            {
              name: '成本分布',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: mockData.costDistribution
            }
          ]
        }
      } else {
        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: '{b}: {c}元'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: mockData.costDistribution.map(item => item.name)
          },
          yAxis: {
            type: 'value',
            name: '金额(元)'
          },
          series: [
            {
              name: '成本金额',
              type: 'bar',
              barWidth: '60%',
              data: mockData.costDistribution.map(item => ({
                value: item.value,
                itemStyle: {
                  color: getColorForCostType(item.name)
                }
              }))
            }
          ]
        }
      }
      
      costDistributionChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        costDistributionChartInstance.resize()
      })
    }
    
    // 初始化成本趋势图表
    const initCostTrendChart = () => {
      if (costTrendChartInstance) {
        costTrendChartInstance.dispose()
      }
      
      costTrendChartInstance = echarts.init(costTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}元<br/>`
            })
            return result
          }
        },
        legend: {
          data: mockData.costTrend.series.map(item => item.name),
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: mockData.costTrend.categories
        },
        yAxis: {
          type: 'value',
          name: '金额(元)'
        },
        series: mockData.costTrend.series.map(item => ({
          name: item.name,
          type: 'line',
          stack: '总量',
          areaStyle: {
            opacity: 0.3
          },
          emphasis: {
            focus: 'series'
          },
          data: item.data,
          itemStyle: {
            color: getColorForCostType(item.name)
          }
        }))
      }
      
      costTrendChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        costTrendChartInstance.resize()
      })
    }
    
    // 更新车辆对比图表
    const updateVehicleCompareChart = () => {
      if (vehicleCompareChartInstance) {
        vehicleCompareChartInstance.dispose()
      }
      
      vehicleCompareChartInstance = echarts.init(vehicleCompareChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const value = params[0].value
            const unit = vehicleCompareMode.value === 'total' ? '元' : '元/公里'
            return `${params[0].name}: ${value}${unit}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.vehicleCompare.vehicles,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: vehicleCompareMode.value === 'total' ? '金额(元)' : '金额(元/公里)'
        },
        series: [
          {
            name: vehicleCompareMode.value === 'total' ? '总成本' : '平均成本/公里',
            type: 'bar',
            barWidth: '50%',
            data: vehicleCompareMode.value === 'total' 
              ? mockData.vehicleCompare.totalCost
              : mockData.vehicleCompare.averageCost,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      }
      
      vehicleCompareChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        vehicleCompareChartInstance.resize()
      })
    }
    
    // 处理日期变化
    const handleDateChange = () => {
      loadData()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    // 获取成本类型标签颜色
    const getCostTypeTag = (type) => {
      const types = {
        fuel: 'danger',
        etc: 'warning',
        repair: 'primary',
        insurance: 'success',
        inspection: 'info'
      }
      return types[type] || ''
    }
    
    // 获取成本类型名称
    const getCostTypeName = (type) => {
      const names = {
        fuel: '油费',
        etc: 'ETC费用',
        repair: '维修费用',
        insurance: '保险费用',
        inspection: '年检费用'
      }
      return names[type] || type
    }
    
    // 获取成本类型对应颜色
    const getColorForCostType = (typeName) => {
      const colors = {
        '油费': '#F56C6C',
        'ETC费用': '#E6A23C',
        '维修费用': '#409EFF',
        '保险费用': '#67C23A',
        '年检费用': '#909399'
      }
      return colors[typeName] || '#409EFF'
    }
    
    // 格式化货币
    const formatCurrency = (value, isSmall = false) => {
      if (isSmall) {
        return value.toFixed(2) + '元'
      }
      return value.toLocaleString('zh-CN', { 
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + '元'
    }
    
    // 导出Excel
    const exportToExcel = () => {
      ElMessage.success('报表导出成功')
      // 实际项目中应调用导出API
      // window.location.href = '/api/reports/cost-analysis/export?startDate=' + dateRange.value[0] + '&endDate=' + dateRange.value[1]
    }
    
    // 日期格式化
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    return {
      vehicles,
      selectedVehicle,
      dateRange,
      dateShortcuts,
      costType,
      chartType,
      timeUnit,
      vehicleCompareMode,
      costRecords,
      currentPage,
      pageSize,
      total,
      totalCost,
      averageCostPerVehicle,
      averageCostPerKm,
      costDistributionChart,
      costTrendChart,
      vehicleCompareChart,
      loadData,
      handleDateChange,
      handleSizeChange,
      handleCurrentChange,
      updateCharts,
      updateVehicleCompareChart,
      getCostTypeTag,
      getCostTypeName,
      formatCurrency,
      exportToExcel
    }
  }
}
</script> 